package com.yzt.loginmodule.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.loginmodule.regist.RegisterUploadAvatarActivity;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.mvp.MVPActivity;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.user.LoginBean;
import com.yzt.zhuju.network.entity.user.UserLoginInfo;
import com.yzt.zhuju.utils.SpannableFactory;
import com.yzt.loginmodule.R;
import com.yzt.p_base.utils.DisplayUtils;

import cn.jiguang.verifysdk.api.AuthPageEventListener;
import cn.jiguang.verifysdk.api.JVerificationInterface;
import cn.jiguang.verifysdk.api.JVerifyUIClickCallback;
import cn.jiguang.verifysdk.api.JVerifyUIConfig;
import cn.jiguang.verifysdk.api.VerifyListener;

/**
 * 登录界面
 */
@SuppressLint("NonConstantResourceId")
@Route(path = RouterAccount.ACTIVITY_LOGIN)
public class OneKeyLoginActivity extends MVPActivity<LoginPresenterImpl> implements LoginContract.View {

    private static final String TAG = "OneKeyLoginActivity";

    /**
     * 开启
     */
    public static void startSelf(Activity activity) {
        if (activity == null) {
            return;
        }
        Intent intent = new Intent(activity, OneKeyLoginActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_one_key_login;
    }

    @Override
    public void installViews() {
        loginAuth();
    }

    /**
     * 一键登录
     */
    private void loginAuth() {

        JVerifyUIConfig portrait = getFullScreenPortraitConfig();
        JVerificationInterface.setCustomUIWithConfig(portrait);
        JVerificationInterface.clearPreLoginCache();

        //autoFinish 可以设置是否在点击登录的时候自动结束授权界面
        JVerificationInterface.loginAuth(this, false, new VerifyListener() {
            @Override
            public void onResult(final int code, final String content, final String operator) {
                Log.e(TAG, "[" + code + "]message=" + content + ", operator=" + operator);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (code == 6000) {
                            login(content);
                            Log.e("tag", "one key code ---->" + content);
                        } else {
                            JVerificationInterface.dismissLoginAuthActivity();
                            RouterAccount.SMSLoginActivity(mActivity, "", "86", 1, true);
                            OneKeyLoginActivity.this.finish();
                        }
                    }
                });
            }
        }, new AuthPageEventListener() {
            @Override
            public void onEvent(int cmd, String msg) {
                Log.e(TAG, "[onEvent]. [" + cmd + "]message=" + msg);
                if (cmd == 1) {
                    OneKeyLoginActivity.this.finish();
                }
            }
        });
    }

    public void login(String token) {
        BizLayer.getInstance().getAccountModule().oneKeyLogin(token,
                new AresSubscriber<LoginBean>() {
                    @Override
                    protected void onSuccess(LoginBean userLoginInfo) {
                        UserLoginInfo info = new UserLoginInfo();
                        info.setAuthed(userLoginInfo.isRegistered());
                        info.setToken(userLoginInfo.getToken());
                        UserLoginInfo.LoginInfo loginInfo = new UserLoginInfo.LoginInfo();
                        loginInfo.setUid(userLoginInfo.getUserId());
                        info.setUserInfo(loginInfo);
                        RXingUtils.saveLoginAccount(info);
                        if (userLoginInfo.isRegistered()) {
                            RouterMain.MainActivity();
                        } else {
                            Intent intent = new Intent(mActivity, RegisterUploadAvatarActivity.class);
                            startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(mActivity).toBundle());
                        }
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    protected void onFinallyEnd() {
                        super.onFinallyEnd();
                        closeProgress();
                    }
                });
    }

    private JVerifyUIConfig getFullScreenPortraitConfig() {
        JVerifyUIConfig.Builder uiConfigBuilder = new JVerifyUIConfig.Builder();
        uiConfigBuilder.setAuthBGImgPath("icon_one_key_bg");
        uiConfigBuilder.setLogoOffsetY(103);
        uiConfigBuilder.setNumFieldOffsetY(190);
        uiConfigBuilder.setPrivacyState(true);

        // 标题栏
        uiConfigBuilder.setNavHidden(false);
        uiConfigBuilder.setNavTransparent(true);
        uiConfigBuilder.setNavHidden(true);
        uiConfigBuilder.setNavReturnImgPath("vector_fork");

        // logo
        uiConfigBuilder.setLogoImgPath("icon_onekey_logo");
        uiConfigBuilder.setLogoHeight(99);
        uiConfigBuilder.setLogoWidth(99);
        uiConfigBuilder.setLogoOffsetY(74);

        // 电话号码
        uiConfigBuilder.setNumberColor(0xFFFFFFFF);
        uiConfigBuilder.setNumberSize(34);
        uiConfigBuilder.setNumFieldOffsetY(249);

        // slogan
        uiConfigBuilder.setSloganTextSize(12);
        uiConfigBuilder.setSloganTextColor(0xFFFFFFFF);
        uiConfigBuilder.setSloganOffsetY(305);

        // 一键登录按钮
        uiConfigBuilder.setLogBtnImgPath("icon_img_onekey_login");
        uiConfigBuilder.setLogBtnTextColor(0xFFFFFFFF);
        uiConfigBuilder.setLogBtnText("一键登录");
        uiConfigBuilder.setLogBtnTextSize(18);
        uiConfigBuilder.setLogBtnOffsetY(382);
        uiConfigBuilder.setLogBtnWidth(333);
        uiConfigBuilder.setLogBtnHeight(60);

        // 隐私政策模块
        uiConfigBuilder.setUncheckedImgPath("icon_register_checkbox_uncheck");
        uiConfigBuilder.setCheckedImgPath("icon_register_checkbox_check");
        uiConfigBuilder.setPrivacyCheckboxSize(12);
        uiConfigBuilder.setAppPrivacyColor(0xFF777777, 0xFFFFFFFF);

        uiConfigBuilder.setPrivacyText("我已阅读并同意《", "", "", "并授权煮桔获取本机号码");
        uiConfigBuilder.setAppPrivacyOne("》《用户服务协议", getString(R.string.user_agreement_url));
        uiConfigBuilder.setAppPrivacyTwo("》《隐私协议》", getString(R.string.privacy_policy_url));
        uiConfigBuilder.setPrivacyCheckboxHidden(false);
        uiConfigBuilder.setPrivacyState(false);
        uiConfigBuilder.setPrivacyTextCenterGravity(true);
        uiConfigBuilder.setPrivacyTextSize(12);

        Toast showToast = Toast.makeText(getContext(), "请先阅读并同意以下的协议", Toast.LENGTH_SHORT);
        uiConfigBuilder.enableHintToast(true, showToast);

        // 手机登录按钮
        RelativeLayout.LayoutParams layoutParamPhoneLogin = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParamPhoneLogin.setMargins(0, DisplayUtils.dp2px(464.0f), 0, 0);
        layoutParamPhoneLogin.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        layoutParamPhoneLogin.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);

        // 其他方式登录
        TextView tvPhoneLogin = new TextView(this);
        tvPhoneLogin.setText(SpannableFactory.create("其他方式登录")
                .foregroundResColor(R.color.color_777777)
                .fontSize(14, true)
                .build());
        tvPhoneLogin.setGravity(Gravity.CENTER);
        tvPhoneLogin.setBackground(getDrawable(R.drawable.shape_onekey_other));
        tvPhoneLogin.setLayoutParams(layoutParamPhoneLogin);
        uiConfigBuilder.addCustomView(tvPhoneLogin, false, new JVerifyUIClickCallback() {
            @Override
            public void onClicked(Context context, View view) {
                JVerificationInterface.dismissLoginAuthActivity();
                RouterAccount.SMSLoginActivity(mActivity, "", "86", 1, true);
                OneKeyLoginActivity.this.finish();
            }
        });

        final View dialogViewTitle = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_login_title, null, false);

        uiConfigBuilder.addNavControlView(dialogViewTitle, new JVerifyUIClickCallback() {
            @Override
            public void onClicked(Context context, View view) {
                if (view.getId() == R.id.img_back) {
                    JVerificationInterface.dismissLoginAuthActivity();
                    RouterAccount.SMSLoginActivity(mActivity, "", "86", 1, true);
                    OneKeyLoginActivity.this.finish();
                }
            }
        });

        return uiConfigBuilder.build();
    }
}